<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/12
 * Time: 14:28
 */

namespace fastphp\base;


class View
{
    protected $controller;

    protected $action;

    protected $variables = [];

    /**
     * View constructor.
     * @param $controller
     * @param $action
     */
    public function __construct($controller, $action)
    {
        $this->controller = $controller;
        $this->action = $action;
    }

    public function assign($name,$value){
        $this->variables[$name] = $value;
    }

    // 渲染显示
    public function render()
    {
        //将数组键值对赋值为变量
        extract($this->variables);

        //默认页头页脚
        $defaultHeader = APP_PATH . 'app'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'header.php';
        $defaultFooter = APP_PATH . 'app'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR.'footer.php';

        //控制器页头页脚
        $controllerHeader = APP_PATH . 'app'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR . $this->controller .DIRECTORY_SEPARATOR.'header.php';
        $controllerFooter = APP_PATH . 'app'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR . $this->controller .DIRECTORY_SEPARATOR.'footer.php';
        $controllerLayout = APP_PATH . 'app'.DIRECTORY_SEPARATOR.'views'.DIRECTORY_SEPARATOR . $this->controller .DIRECTORY_SEPARATOR . $this->action . '.php';

        // 页头文件
        if (is_file($controllerHeader)) {
            include ($controllerHeader);
        } else {
            include ($defaultHeader);
        }

        //判断视图文件是否存在
        if (is_file($controllerLayout)) {
            include ($controllerLayout);
        } else {
            echo "<h1>无法找到视图文件</h1>";
        }

        // 页脚文件
        if (is_file($controllerFooter)) {
            include ($controllerFooter);
        } else {
            include ($defaultFooter);
        }
    }

}